"""XML Utility function module is used to handle XML files

XMLMinidomHandler is used to parse and deal with an XML in a tree format

"""

# TODO: Complete the functions in this module :(

import xml.dom
import xml.dom.minidom as minidom
import os.path
import logging
import logging.config
import ma.log


class XMLMinidomHandler(object):
    root_node = None
    
    def __init__(self, filepath):
        #initialize __log for XMLMinidomHandler
        self.__log = ma.log.get_logger("ma.utils")
        
        if(os.path.exists(filepath)):
            # incase the file already exists
            self.__log.info("Starting to parse the XML file: " + filepath)
            self.__dom_tree = minidom.parse(filepath)
            self.__log.info("Finished parsing the XML file: " + filepath)
            self.root_node = self.__dom_tree
        else:
            # incase the file didn't exist before
            self.__log.info("Creating new XML Document: " + filepath)
            self.__dest_filepath = filepath
            self.__dom_tree = minidom.Document()
            self.root_node = None                   # set root node to None
    
    def clear_and_set_root_node(self, root_name):
        self.__dom_tree = minidom.Document()
        self.root_node = self.__dom_tree.createElement(root_name)
        self.__dom_tree.appendChild(self.root_node)
        
    def move_to_node(self, node):
        i = 0
        
    def add_text_node(self, element_name, text, attributes_dict):
        pass
    
    def remove_node(self, node):
        pass
        
    def clear_xml_dom_tree(self, node):
        pass
    
    def get_text_nodes_for_name_unicode(self, element_name):
        pass
    
    def get_text_nodes_for_name_str(self, element_name):
        pass
    
    def get_text_nodes_for_name_int(self, element_name):
        pass
                
    def write_to_file(self, node):
        pass
    
    # Courtesy: Ron Rothman
    # http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/
    def fixed_writexml(self, element = root_node, writer, indent="", addindent="", newl=""):
        # indent = current indentation
        # addindent = indentation to add to higher levels
        # newl = newline string
        writer.write(indent+"<" + element.tagName)
    
        attrs = element._get_attributes()
        a_names = list(attrs.keys())
        a_names.sort()
    
        for a_name in a_names:
            writer.write(" %s=\"" % a_name)
            xml.dom.minidom._write_data(writer, attrs[a_name].value)
            writer.write("\"")
        if element.childNodes:
            if len(element.childNodes) == 1 \
              and element.childNodes[0].nodeType == xml.dom.minidom.Node.TEXT_NODE:
                writer.write(">")
                self.fixed_writexml(element.childNodes[0], writer, "", "", "")
                writer.write("</%s>%s" % (element.tagName, newl))
                return
            writer.write("<%s"%(newl))
            for node in element.childNodes:
                self.fixed_writexml(node, writer, indent+addindent, addindent, newl)
            writer.write("%s</%s>%s" % (indent, element.tagName, newl))
        else:
            writer.write("/>%s"%(newl))

    def __del__(self):
        """Destructor"""
        self.__dom_tree.unlink()
        
